﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.ByteBuffer;
using tools;

namespace WindowsFormsApplication2
{
   public class Message
    {
       public const short PACK_MARK = 0x0000;
        /** 信息头 */
       public Header header;
        /** 信息体 */
       public byte[] body = new byte[0];
        /** 通信附加信息体 */
       public byte[] attachment = new byte[0];

        public static Message ValueOf(Header _hander,byte[] body) {
            Message message = new Message();
            message.header = _hander;
            message.body = body;
            return message;
        }

        public static Message ValueOf(byte module,byte command, byte[] body)
        {
            Message message = new Message();
            message.header = Header.ValueOf(1, 0, 1, module, command);
            message.body = body;
            return message;
        }

        public static Message Format(byte[] byteArray) {
            Message message = new Message();
            MyConverter con = new MyConverter(byteArray);
            short mark = con.toInt16();
            short packLen = con.toInt16();
            message.header = Header.Format(con);
            int bodyLen = con.toInt16();
            message.body = con.copyByte(bodyLen);
            return message;
        }

        public byte[] ToByteArray() {
            ByteBuffer byteMessage = new ByteBuffer();
            byteMessage.PushByteArray(this.header.ToByteArray());//消息头内容
            byteMessage.PushShort(this.body.Length); //消息内容长头
            byteMessage.PushByteArray(this.body); //消息内容
            byte[] package =  byteMessage.ToByteArray();

            ByteBuffer  byteList = new ByteBuffer();
            byteList.PushShort(PACK_MARK);//包标识
            byteList.PushShort(package.Length); //内体内容长度
            byteList.PushByteArray(package);//内容

            return byteList.ToByteArray();
        }

        public String ToString() {
            return "Message:["+header.toString() + "[B:" + body.Length + "]]";
        }
    }
}
